'use strict';

layui.define(['view', 'helper', 'loading'], function(exports) {
  var $ = layui.jquery;
  var element = layui.element;
  var view = layui.view;
  var helper = layui.helper;
  var loading = layui.loading;
  var debug = layui.hint();

  var MODULE_NAME = 'pagetabs';

  var ClassName = {
    SHOW        : 'layui-show',
    THIS        : 'layui-this',
    CONTEXT_MENU: 'layadmin-pagetabs-contextmenu',
    BACKDROP    : 'layadmin-pagetabs-backdrop'
  };

  var $window = $(window);
  var $body = $('body');

  function Pagetabs() {
    this.selector = null;
    this.basePath = '';
    this.cache = {};
    this.LAY_FILTER = '';
  }

  Pagetabs.prototype.render = function(selector, basePath) {
    this.selector = selector;
    this.basePath = basePath;

    var $el = $(selector);
    if ($el.length !== 1) return;

    this.LAY_FILTER = $el.attr('lay-filter');
    // 右键菜单
    var $menu = $('.' + ClassName.CONTEXT_MENU);
    if ($menu.length <= 0) {
      $menu = $([
        '<ul class="' + ClassName.CONTEXT_MENU + '">',
        '<li layadmin-pagetabs-event="refresh"><a href="javascript:;">刷新</a></li>',
        '<li layadmin-pagetabs-event="close"><a href="javascript:;">关闭当前</a></li>',
        '<li layadmin-pagetabs-event="closeOther"><a href="javascript:;">关闭其他</a></li>',
        '<li layadmin-pagetabs-event="closeAll"><a href="javascript:;">关闭全部</a></li>',
        '<li layadmin-pagetabs-event="openWindow"><a href="javascript:;">新窗口</a></li>',
        '</ul>'
      ].join(''));
      $menu.hide();
      $body.append($menu);
      Pagetabs['@@menuWidth'] = $menu.outerWidth();
    }
    // 右键菜单背景
    var $backdrop = $('.' + ClassName.BACKDROP);
    if ($backdrop.length <= 0) {
      $backdrop = $('<div class="' + ClassName.BACKDROP + '" layadmin-pagetabs-event="closeContextMenu"></div>');
      $body.append($backdrop);
    }

    $.extend(this.cache, {
      $el      : $el,
      $title   : $el.find('.layui-tab-title'),
      $content : $el.find('.layui-tab-content'),
      $backdrop: $backdrop,
      $menu    : $menu
    });

    this.bindEvents();

    return this;
  };

  Pagetabs.prototype.bindEvents = function() {
    var _this = this;
    var $title = this.cache.$title;
    var $backdrop = this.cache.$backdrop;
    var $menu = this.cache.$menu;

    var events = {
      closeContextMenu: function() {
        _this.closeContextMenu();
      },
      refresh: function() {
        var layId = $menu.attr('lay-id');
        _this.refresh(layId);
        events.closeContextMenu();
      },
      close: function() {
        var layId = $menu.attr('lay-id');
        _this.close(layId);
        events.closeContextMenu();
      },
      closeOther: function(type) {
        var layId = $menu.attr('lay-id');
        _this.closeOther(layId, type);
        events.closeContextMenu();
      },
      closeAll: function() {
        events.closeOther('all');
      },
      openWindow: function() {
        var layId = $menu.attr('lay-id');
        var path = $title.find('li[lay-id="' + layId + '"]').attr('lay-attr');

        if (path) {
          window.open(path);
        } else {
          view.error('无法打开此窗口');
        }
        events.closeContextMenu();
      }
    };

    $body.off('click.' + MODULE_NAME).on('click.' + MODULE_NAME, '*[layadmin-pagetabs-event]', function() {
      var eventName = $(this).attr('layadmin-pagetabs-event');
      var disabled = $(this).data('disabled');
      !disabled && $.isFunction(events[eventName]) && events[eventName].call(this);
    });

    $menu.on('contextmenu', function(e) {
      e.preventDefault();
    });

    $backdrop.on('contextmenu', function(e) {
      e.preventDefault();
      events.closeContextMenu();
    });

    $title.off('contextmenu.' + MODULE_NAME).on('contextmenu.' + MODULE_NAME, 'li', function(e) {
      var $this = $(this);
      var $target = $title.find('li.' + ClassName.THIS);
      var winWidth = $window.width();
      var menuWidth = Pagetabs['@@menuWidth'];
      var mouseX = e.clientX;
      var isLock = helper.isString($this.attr('lay-lock'));

      e.preventDefault();

      $menu.find('li[layadmin-pagetabs-event]').removeClass('is-disabled').data('disabled', false);
      $target.attr('lay-id') !== $this.attr('lay-id') && $menu.find('li[layadmin-pagetabs-event="refresh"]').addClass('is-disabled').data('disabled', true);
      isLock && $menu.find('li[layadmin-pagetabs-event="close"]').addClass('is-disabled').data('disabled', true);
      $backdrop.show();
      $menu.show().attr('lay-id', $(this).attr('lay-id')).css({
        top     : e.clientY,
        left    : (winWidth - mouseX < menuWidth + 5) ? (winWidth - menuWidth - 5) : mouseX,
        minWidth: menuWidth
      });
    });
  };

  Pagetabs.prototype.exist = function(layId) {
    var tabIndex = -1;

    this.cache.$title.find('li').each(function(index, item) {
      if (layId === $(item).attr('lay-id')) {
        tabIndex = index;
        return false;
      }
    });

    return tabIndex;
  };

  Pagetabs.prototype.getCurrentId = function() {
    return this.cache.$title.find('.' + ClassName.THIS).attr('lay-id');
  };

  Pagetabs.prototype.add = function(option /* { url, id, text, tips } */) {
    var isObject = helper.isObject(option);
    if (!isObject || (isObject && !option.url)) return;

    // var $content = this.cache.$content;
    var index = this.exist(option.id);

    option.url = helper.resolvePath(this.basePath, option.url);

    if (index === -1) {
      // if ($content.children('.layadmin-loading').length >= 0) {
      //   view.removeLoading();
      // }
      // view.loading($content);

      loading.start();

      element.tabAdd(this.LAY_FILTER, {
        content: '<iframe src="' + option.url + '" name="' + option.id + '" allowfullscreen="allowfullscreen" frameborder="no"></iframe>',
        title  : '<span>' + (option.text || '未知标签') + '</span>',
        attr   : option.url,
        id     : option.id
      });

      this.cache.$el.find('iframe[name="' + option.id + '"]').on('load', function() {
        // view.removeLoading();
        loading.finish();
      });

      option.tips && this.cache.$title.find('li[lay-id="' + option.id + '"]').data('tips', option.tips);

      setTimeout(function() {
        // view.removeLoading();
        loading.finish();
      }, 1e4);
    }

    return this.change(option.id);
  };

  Pagetabs.prototype.change = function(layId) {
    layId && element.tabChange(this.LAY_FILTER, layId);
    return this;
  };

  Pagetabs.prototype.refresh = function() {
    var $title = this.cache.$title;
    var $content = this.cache.$content;

    var layId = arguments.length > 0 ? arguments[0] : $title.find('li.' + ClassName.THIS).attr('lay-id');
    var iframe = $content.find('iframe[name="' + layId + '"]')[0];
    var location = iframe && iframe.contentWindow && iframe.contentWindow.location;
    $.isFunction(location.reload) && location.reload(true);
    return this.change(layId);
  };

  Pagetabs.prototype.close = function() {
    var $title = this.cache.$title;
    var layId = arguments.length > 0 ? arguments[0] : $title.find('li.' + ClassName.THIS).attr('lay-id');
    var lock = helper.isString($title.find('li[lay-id="' + layId + '"]').attr('lay-lock'));
    !lock && element.tabDelete(this.LAY_FILTER, layId);
    // view.removeLoading(this.cache.$content);
    return this;
  };

  Pagetabs.prototype.closeOther = function(layId, type) {
    var $title = this.cache.$title;
    var $content = this.cache.$content;

    $title.find('li').each(function(index, item) {
      var $this = $(item);
      if (type === 'all' || $this.attr('lay-id') !== layId) {
        if (!helper.isString($this.attr('lay-lock'))) {
          $this.remove();
          $content.find('.layui-tab-item:eq(' + index + ')').remove();
        }
      }
    });

    $title.find('li:last-child').addClass(ClassName.THIS);
    $content.find('.layui-tab-item:last-child').addClass(ClassName.SHOW);
    // view.removeLoading(this.cache.$content);
    return this;
  };

  Pagetabs.prototype.closeAll = function(layId, type) {
    return this.closeOther(layId, type);
  };

  Pagetabs.prototype.closeContextMenu = function() {
    var $menu = this.cache.$menu;
    var $backdrop = this.cache.$backdrop;
    $menu.hide().removeAttr('lay-id');
    $backdrop.hide();
    return this;
  };

  Pagetabs.prototype.getCurrentInfo = function() {
    var ret;
    var $title = this.cache.$title;
    var $targetTitle = $title.find('li.' + ClassName.THIS);

    if ($targetTitle.length !== 1) {
      debug.error('无法确定获取当前选项卡');
    } else {
      ret = {
        url : $targetTitle.attr('lay-attr'),
        id  : $targetTitle.attr('lay-id'),
        text: $targetTitle.text(),
        tips: $title.data('tips')
      };
    }

    return helper.isDef(ret) ? this : ret;
  };

  exports(MODULE_NAME, new Pagetabs());
});
